"use strict";
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var pool = [];
var getItemByKey = function (key) { return pool.filter(function (k) { return k.key === key; }); };
var getItemByUid = function (uid) { return pool.find(function (k) { return k.uid === uid; }); };
var getItemIdxByUid = function (uid) { return pool === null || pool === void 0 ? void 0 : pool.findIndex(function (k) { return k.uid === uid; }); };
var removeItem = function (uid) { return pool.splice(getItemIdxByUid(uid), 1); };
wx.$events = {
    $hasListeners: function (key) {
        return getItemByKey(key).length > 0;
    },
    $emit: function (key) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        getItemByKey(key).forEach(function (item) {
            item.fn.apply(item, args);
            if (item.isOnce)
                removeItem(item.uid);
        });
    },
    $on: function (key, fn, isOnce) {
        pool.push({
            uid: "".concat(pool.length, "-").concat(Math.random().toString().slice(2, 16)).padStart(18, 'x'),
            key: String(key),
            fn: fn,
            isOnce: isOnce
        });
    },
    $once: function () {
        var _a;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        return (_a = wx.$events).$on.apply(_a, __spreadArray(__spreadArray([], args, false), [true], false));
    },
    $off: function (key) { getItemByKey(key).forEach(function (k) { return removeItem(k.uid); }); },
};
